<template>
  <div class="h-full flex flex-col overflow-auto">
    <ReadCard business-type="出院退费" module-type="住院" :call-back-data="patientData" @read="getPatientInfoByID" @tab-change="onTabChange">
      <template #selfCost>
        <!-- <a-card> -->
        <a-form ref="formRef" :model="formState" class="flex justify-between">
          <div class="flex">
            <a-form-item name="brName" class="w-[260px] mr-3 !mb-0">
              <SelectTable
                v-model:value="formState.brName"
                type="住院登记退费人员"
                :search-params="{ jslx: 'CWGL' }"
                table-width="660"
                placeholder="姓名/助记码/住院号"
                @select="onSelect"
              />
            </a-form-item>
          </div>
          <div>
            <a-button style="margin: 0 8px" @click="onClickReset">重置</a-button>
            <a-button type="primary" @click="handleSearch">刷新</a-button>
          </div>
        </a-form>
        <!-- </a-card> -->
      </template>
      <template v-if="tabActiveKey !== '自费'" #rightBtn>
        <div class="w-[280px] flex items-center justify-end shrink-0">
          <span class="mr-2 font-bold">医保结算</span>
          <a-switch v-model:checked="isUseCHS" class="mr-4" />
          <a-button class="mx-2" @click="onClickReset">重置</a-button>
          <a-button type="primary" @click="handleSearch">刷新</a-button>
        </div>
      </template>
    </ReadCard>
    <!-- <a-card>
      <a-form ref="formRef" :model="formState" class="flex justify-between form-style-flex">
        <div class="flex">
          <a-form-item name="brName" class="w-[330px] mr-3 !mb-0">
            <SelectTable
              v-model:value="formState.brName"
              type="住院登记退费人员"
              :search-params="{ jslx: 'CWGL' }"
              table-width="660"
              placeholder="姓名/助记码/住院号"
              @select="onSelect"
            />
          </a-form-item>
        </div>
        <div>
          <a-button style="margin: 0 8px" @click="onClickReset">重置</a-button>
          <a-button type="primary" @click="handleSearch">刷新</a-button>
        </div>
      </a-form>
    </a-card> -->
    <PatientInfoHeader :patient-info="patientData" show-insurance :show-user-info="false" class="mt-2" @change="onClickReset">
      <a-divider type="vertical" :style="{ height: '40px', margin: '0 16px' }" />
      <div>
        <div class="flex items-center">
          <LabelValue label="住院号" :value="patientData.admissionCode" :width="220" />
          <LabelValue label="入院时间" :value="patientData.admissionTime" :width="220" />
          <LabelValue label="出院科室" :value="patientData.ksmc" :width="220" />
          <LabelValue label="住院费用" :value="formatMoney(patientData.ypzje)" :width="220" />
          <LabelValue label="票据号" :value="patientData.pjhm" :width="220" />
        </div>
        <div class="flex items-center">
          <LabelValue label="住院天数" :value="formatDay(patientData.zyts)" :width="220" />
          <LabelValue label="出院时间" :value="patientData.dischargeDate" :width="220" />
          <LabelValue label="出院病区" :value="patientData.wardName" :width="220" />
          <LabelValue label="支付方式" :value="patientData.memo" tooltip :width="300" />
        </div>
      </div>
    </PatientInfoHeader>
    <div class="mt-2 flex flex-1 overflow-hidden">
      <div class="w-3/5 mr-2 relative overflow-auto">
        <a-card>
          <BaseTitle title="收费明细" class="!mb-2.5">
            <template v-if="isSystemOpenCHS && isUseCHS">
              <div class="flex justify-end">
                <BaseButton type="primary" class="mr-2" :disabled="!patientData.inplsh" ghost comfirm-text="确认处方撤销？" @click="onRxUploadCancel()">
                  处方撤销
                </BaseButton>
                <BaseButton type="primary" comfirm-text="确认处方上传？" :disabled="!patientData.inplsh" ghost class="mr-2" @click="onRxUpload()">
                  处方上传
                </BaseButton>
              </div>
            </template>
          </BaseTitle>
          <BaseTable
            :loading="loading"
            column-code="000401"
            :scroll="{ x: 1000 }"
            :height="getLeftTableHeight()"
            :data-source="tableDataDetail"
            bordered
            :row-class-name="(_record) => rowClass(_record)"
          >
            <template #bodyCell="{ column, index, record }">
              <template v-if="column.dataIndex === 'xh'">
                {{ index + 1 }}
              </template>
              <template v-if="column.dataIndex === 'advName'">
                <div class="flex items-center truncate">
                  <div :title="record.mc">{{ record.advName }}</div>
                  <div v-if="record.spc" :title="record.spc" :class="specClass(record)">{{ record.spc }}</div>
                </div>
              </template>
            </template>
          </BaseTable>
        </a-card>
      </div>
      <div class="w-2/5 flex flex-col overflow-auto">
        <a-card class="w-full">
          <BaseTitle title="收费类别" class="!mb-2.5" />
          <BaseTable :loading="loading" column-code="000402" :data-source="tableDataType" bordered :height="getRightTableHeight()">
            <template #bodyCell="{ column, index }">
              <template v-if="column.dataIndex === 'xh'">
                {{ index + 1 }}
              </template>
            </template>
            <template #footer>
              <div class="text-right w-full px-4">
                医疗费：<span class="text-xl font-bold text-red-500">￥{{ formatAmount(allData.amountStr) }}</span>
              </div>
            </template>
          </BaseTable>
        </a-card>
        <a-card v-if="isSystemOpenCHS" class="mt-2">
          <BaseTitle title="医保结算" class="!mb-0">
            <a-button type="primary" size="small" :disabled="!formState.brName" @click="onPreSettlement()">预结算</a-button>
          </BaseTitle>
          <div class="flex justify-between flex-wrap mt-4">
            <div class="w-1/2 mb-2">
              <span class="inline-block w-32 text-right">医疗总金额: </span>
              <span class="text-base">￥{{ formatAmount(preSettlementInfo.outPocketAmountResponse?.ysje || 0) }}</span>
            </div>
            <div class="w-1/2 mb-2">
              <span class="inline-block w-32 text-right">账户余额: </span>
              <span class="text-base">￥{{ formatAmount(preSettlementInfo.outPocketAmountResponse?.zhye || 0) }}</span>
            </div>
            <div class="w-1/2 flex items-center">
              <span class="inline-block w-32 text-right">医保支付: </span>
              <span class="text-base">￥{{ formatAmount(preSettlementInfo.outPocketAmountResponse?.ybzf || 0) }}</span>
              <a-popover trigger="click">
                <template #content> <CHSPopover :data="preSettlementInfo.medicareAmountResponse" /> </template>
                <a-button size="small" class="ml-2" shape="circle">
                  <span class="text-sm">?</span>
                </a-button>
              </a-popover>
            </div>
            <div class="w-1/2">
              <span class="inline-block w-32 text-right">未贯标金额: </span>
              <span class="text-base">￥{{ formatAmount(preSettlementInfo.outPocketAmountResponse?.wgbje || 0) }}</span>
            </div>
          </div>
        </a-card>
        <div class="flex flex-col relative w-full">
          <a-card class="mt-2 bottom-0 w-full sticky border-t">
            <div class="text-right mr-2 mb-2">
              <div v-if="patientData.chargeStatus === 2" class="my-2 font-semibold">
                <div class="flex justify-end items-end">
                  <div>原住院费用:</div>
                  <div class="inline-block text-2xl font-bold text-left">￥{{ formatAmount(allData.yzyfy) }}</div>
                  <CaretUpOutlined v-if="tranActive" class="ml-1 cursor-pointer" :style="{ fontSize: '24px' }" @click="tranActive = false" />
                  <CaretDownOutlined v-else class="ml-1 cursor-pointer" :style="{ fontSize: '24px' }" @click="tranActive = true" />
                </div>
                <span v-if="!tranActive" class="inline-block mr-7 text-slate-400">
                  <span class="block text-left">医保支付(原): ￥{{ formatAmount(allData.ybje) }}</span>
                  <span class="block text-left">自费支付(原): ￥{{ formatAmount(allData.zfje) }}</span>
                </span>
              </div>
              <div class="my-2 font-semibold">
                <span>住院费用:</span> <span class="inline-block text-2xl font-bold text-left">￥{{ formatAmount(allData.zyfy) }}</span>
              </div>
              <div v-if="patientData.chargeStatus === 2" class="my-2 font-semibold">
                <span>退费差额:</span>
                <span class="inline-block text-2xl font-bold text-red-500 text-left">￥{{ formatAmount(allData.tfce) }}</span>
              </div>
              <div>
                <template v-if="isSystemOpenCHS">
                  <BaseButton
                    v-if="patientData.isNmiYbdj === 1"
                    confirm-text="确认撤销医保登记?"
                    type="primary"
                    class="ml-2"
                    size="large"
                    @click="openMedicalModal"
                  >
                    撤销医保登记
                  </BaseButton>
                  <a-button v-else :disabled="!formState.brName" type="primary" size="large" class="ml-2" ghost @click="openMedicalModal"> 医保登记 </a-button>
                  <a-button v-if="patientData.cydjzt === 1" class="ml-2 w-32" size="large" type="primary" ghost @click="onOutHospitalCancel">
                    撤销出院登记
                  </a-button>
                  <a-button v-else class="ml-2 w-28" size="large" type="primary" :disabled="!formState.brName" ghost @click="outHospitalOpen = true">
                    出院登记
                  </a-button>
                </template>
                <a-button type="primary" :disabled="!formState.brName" class="ml-2 w-28" size="large" ghost @click="printInList">住院清单</a-button>
                <a-button
                  v-if="patientData.chargeStatus === 0 || patientData.chargeStatus === 2"
                  type="primary"
                  class="ml-2 w-28"
                  size="large"
                  :loading="chargeLoading"
                  :disabled="!formState.brName || (tabActiveKey !== '自费' && isUseCHS && patientData.cydjzt === 0)"
                  @click="onSettlement"
                >
                  结算
                </a-button>
                <a-button v-else type="primary" class="ml-2 w-28" size="large" :disabled="!formState.brName" @click="onSettlementCancel"> 撤销结算 </a-button>
              </div>
            </div>
          </a-card>
        </div>
      </div>
    </div>
    <OutHospitalRegister v-model:open="outHospitalOpen" :inplsh="patientData.inplsh" />
    <ChargeModal
      v-model:open="chargeOpen"
      :br-id="patientData.brId"
      source-type="1"
      :business-data="{ ysje: categoryPrice, ...preSettlementInfo, allAmount: preSettlementInfo?.outPocketAmountResponse?.ysje ?? allData.zyfy }"
      @success="onChargeSuccess"
    />
    <!-- 医保登记 -->
    <MedicalRegistration
      v-model:open="medicalOpen"
      :patient-info="{ ...patientData, bedCode: patientData.lastBedCode }"
      :select-name-disabled="true"
      :deposit-type="0"
      @success="getSelectData"
    />
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { message } from 'ant-design-vue'
import { CaretUpOutlined, CaretDownOutlined } from '@ant-design/icons-vue'
import BaseTitle from '@/components/BaseTitle'
import SelectTable from '@/components/SelectTable'
import { formatAmount } from '@/utils/format.js'
import { post } from '@/utils/request'
import BaseTable from '@/components/BaseTable'
import ChargeModal from '../../components/ChargeModal.vue'
import MedicalRegistration from '../../components/MedicalRegistration.vue'
import OutHospitalRegister from '../../hospital-settlement/components/OutHospitalRegister.vue'

const loading = ref(false)
const chargeOpen = ref(false)
// const chargeData = ref({})
const tableDataType = ref([])
const tableDataDetail = ref([])
const formState = ref({
  brName: ''
})
const patientData = ref({})
const allData = ref({})
const categoryPrice = ref(0) // 实收金额
const formRef = ref(null)
const tabActiveKey = ref('自费')
const tranActive = ref(true)

const onTabChange = (e) => {
  tabActiveKey.value = e
  onClickReset()
}
const getLeftTableHeight = () => {
  return window.innerHeight - 365
}
const getSelectData = async () => {
  const { code, data = [], msg } = await post('/inp/inpComprehensive/getRefundSearch', { inplsh: patientData.value.inplsh, jslx: 'CWGL' })
  if (code !== 0) return message.error(msg)
  if (data && data.length > 0) {
    patientData.value = data[0]
  }
  chargeDetailList()
}
const getRightTableHeight = () => {
  let tableHeight = 0
  if (patientData.value.chargeStatus === 2) {
    tableHeight = window.innerHeight - 738
  } else {
    tableHeight = window.innerHeight - 658
  }
  return tableHeight < 240 ? 240 : tableHeight
}
const onSelect = async (select) => {
  formState.value.brName = select.brName
  patientData.value = select
  chargeDetailList()
}

const chargeDetailList = async () => {
  if (!patientData.value.inplsh) return
  const {
    code,
    data = [],
    msg
  } = await post('/inp/inpComprehensive/getUnpaidPatientBillList', {
    inplsh: patientData.value.inplsh,
    pjhm: patientData.value.pjhm,
    jslb: 'TF'
  })
  if (code !== 0) return message.error(msg)
  tableDataDetail.value = data.patientBillList
  tableDataType.value = data.patientBillTypeList
  allData.value = data
}
//撤销结算
const onSettlementCancel = async () => {
  const { code, msg } = await post(
    '/inp/inpComprehensive/doSaveCancelSettlement',
    {
      inplsh: patientData.value.inplsh,
      jslx: 'CWGL'
    },
    { loading: true }
  )
  if (code !== 0) return message.error(msg)
  message.success(msg || '操作成功')
  getSelectData()
}
const printInList = async () => {
  const { code, msg, data } = await post('/inp/Print/printAdmissionList', {
    inplsh: patientData.value.inplsh,
    jslb: 'TF'
  })
  if (code !== 0) return message.error(msg)
  window.openExe?.rpt(data) //调用winform打印
}

// 住院结算单据
const onPrint = async () => {
  const { code, msg, data } = await post('/inp/Print/printSettlementDocumentsList', {
    inplsh: patientData.value.inplsh
  })
  if (code !== 0) return message.error(msg)
  window.openExe?.rpt(data) //调用winform打印
}

const onClickReset = () => {
  formState.value = {
    brName: ''
  }
  tableDataType.value = []
  tableDataDetail.value = []
  allData.value = {}
  patientData.value = {}
}
const handleSearch = () => {
  chargeDetailList()
}
const chargeLoading = ref(false)
const onSettlement = async () => {
  chargeLoading.value = true
  const res = await post('/inp/inpComprehensive/getInpExpensesStatus', { inplsh: patientData.value.inplsh })
  chargeLoading.value = false
  if (res.code !== 0) return message.error(res.msg || '结算失败')
  if (!Number(formatAmount(allData.value.tfce))) {
    formatZeroMoney()
  } else {
    // chargeData.value.ssje = allData.value.tfce
    // chargeData.value.zyfy = allData.value.tfce
    // chargeData.value.yjje = allData.value.zyfy
    // chargeData.value.ybzf = 0
    // chargeData.value.grzf = 0
    // chargeData.value.fbwc = 0
    // chargeData.value.ybsj = {}
    if (tabActiveKey.value === '自费') {
      categoryPrice.value = allData.value.tfce
      chargeOpen.value = true
    } else {
      onPreSettlement(true)
    }
  }
}
const formatZeroMoney = async () => {
  const { code, data } = await post('/outp/oupCharge/getChargeTypeList')
  if (code !== 0) return
  const chargeData = {}
  if (data && data.length > 0) {
    data.forEach((item) => {
      chargeData[item.zffsdm] = chargeData[item.zffsdm] ? chargeData[item.zffsdm] : 0
    })
  }
  chargeData.change = 0
  chargeData.fbyh = 0
  chargeData.yhje = 0
  chargeData.ysje = '0.00'
  chargeData.ssje = '0.00'
  if (tabActiveKey.value === '自费') {
    onChargeSuccess(chargeData)
  } else {
    const res = await post(
      '/inp/inpComprehensive/doHospitalizationPreSettlement',
      {
        acct_used_flag: '1',
        inplsh: patientData.value.inplsh,
        ...readCardInfo.value,
        ...readCardInfo.value.baseinfo,
        pjhm: patientData.value.pjhm
      },
      { chargeLoading: true }
    )
    if (res.code !== 0) return message.error(res.msg)
    preSettlementInfo.value = res.data
    allData.value.tfce = res.data?.outPocketAmountResponse?.ssje
    if (!Number(formatAmount(allData.value.tfce))) {
      chargeLoading.value = true
      onChargeSuccess(chargeData)
      setTimeout(() => {
        chargeLoading.value = false
      }, 2000)
    } else {
      chargeOpen.value = true
    }
  }
}
const rowClass = (record) => {
  if (record.status === 1 && record.paymentStatus === 1) {
    return 'text-red-500'
  } else if (record.status === 3 && record.paymentStatus === 0) {
    return 'text-blue-600'
  } else {
    return ''
  }
}
const specClass = (record) => {
  if (record.status === 1 && record.paymentStatus === 1) {
    return 'text-red-500 ml-2 text-xs'
  } else if (record.status === 3 && record.paymentStatus === 0) {
    return 'text-blue-600 ml-2 text-xs'
  } else {
    return 'text-gray-400 ml-2 text-xs'
  }
}
const formatDay = (val) => {
  if (val) {
    return val + '天'
  } else {
    return '0天'
  }
}
const formatMoney = (val) => {
  if (val) {
    return formatAmount(val) + '元'
  } else {
    return '0.00元'
  }
}
const readCardInfo = ref({})
const isUseCHS = ref(true)
const outHospitalOpen = ref(false)
// 上传处方
const onRxUpload = async () => {
  const res = await post(
    '/inp/inpComprehensive/doPrescriptionUpload',
    {
      acct_used_flag: isUseCHS.value ? '1' : '0',
      inplsh: patientData.value.inplsh,
      ...readCardInfo.value,
      ...readCardInfo.value.baseinfo
    },
    { loading: true }
  )
  if (res.code !== 0) return message.error(res.msg)
  message.success(res.msg || '处方上传成功')
}
// 处方撤销
const onRxUploadCancel = async () => {
  const res = await post(
    '/inp/inpComprehensive/doFeeReversal',
    {
      inplsh: patientData.value.inplsh
    },
    { loading: true }
  )
  if (res.code !== 0) return message.error(res.msg)
  message.success(res.msg || '撤销成功')
}
// 登记撤销
const onOutHospitalCancel = async () => {
  const res = await post(
    '/inp/inpComprehensive/doHospitalizationRevokedS',
    {
      inplsh: patientData.value.inplsh,
      ybkh: readCardInfo.value.kh
    },
    { loading: true }
  )
  if (res.code !== 0) return message.error(res.msg)
  message.success(res.msg || '撤销成功')
}
// 医保调试
const getPatientInfoByID = async (res) => {
  readCardInfo.value = res
  const { code, msg, data } = await post('/inp/inpComprehensive/getRefundSearch', {
    brId: res.ybkResonse.br_id,
    jslx: 'CWGL'
  })
  if (code !== 0) return message.error(msg)
  if (data && data.length > 0) {
    formState.value.brName = data[0].brName
    patientData.value = data[0]
    chargeDetailList()
  } else {
    message.error('患者查询为空')
  }
}
const preSettlementInfo = ref({}) //预结算数据
// 预结算
const onPreSettlement = async (isOpen = false) => {
  const res = await post(
    '/inp/inpComprehensive/doHospitalizationPreSettlement',
    {
      acct_used_flag: '1',
      inplsh: patientData.value.inplsh,
      ...readCardInfo.value,
      ...readCardInfo.value.baseinfo,
      pjhm: patientData.value.pjhm
    },
    { loading: true }
  )
  if (res.code !== 0) return message.error(res.msg)
  preSettlementInfo.value = res.data || {}
  allData.value.tfce = res.data?.outPocketAmountResponse?.ssje
  chargeOpen.value = isOpen
}

const onChargeSuccess = async (chargeData = {}) => {
  let verRes = ''
  if (getSystemConfig('NMI_REGION_CODE') === '022' && patientData.value.insutype === '310' && tabActiveKey.value === '社保卡') {
    verRes = await window.openExe?.iVerifyPIN()
  }
  const { code, msg } = await post('/inp/inpComprehensive/doSaveRefundHospitalDischarge', {
    ...chargeData,
    brId: patientData.value.brId,
    tfje: allData.value.tfce,
    ypzje: allData.value.amountStr,
    pjhm: patientData.value.pjhm,
    inplsh: patientData.value.inplsh,
    ...preSettlementInfo.value,
    ...readCardInfo.value,
    ...readCardInfo.value.baseinfo,
    mmJson: verRes ? verRes : undefined
  })
  if (code !== 0) return message.error(msg)
  if (tabActiveKey.value === '自费') {
    message.success(msg)
    onPrint()
    onClickReset()
    chargeOpen.value = false
  } else {
    // const { code, msg } = await post(
    //   '/inp/inpComprehensive/doCancellationHospitalizationMedicalInsuranceExpenses',
    //   {
    //     ...chargeData,
    //     brId: patientData.value.brId,
    //     tfje: allData.value.tfce,
    //     ypzje: allData.value.amountStr,
    //     pjhm: patientData.value.pjhm,
    //     inplsh: patientData.value.inplsh
    //   },
    //   { loading: true }
    // )
    // if (code !== 0) return message.error(msg)
    message.success(msg)
    onPrint()
    onClickReset()
    chargeOpen.value = false
  }
}
const medicalOpen = ref(false)
const openMedicalModal = () => {
  medicalOpen.value = true
}
const isSystemOpenCHS = getSystemConfig('IS_EXIST_MEDICAL_INSURANCE') === '1'
</script>
<style lang="less" scoped>
:deep(.ant-radio-button-wrapper) {
  flex: 1;
  color: var(--primary-color);
  text-align: center;
  border-color: var(--primary-color);
  &::before {
    background-color: var(--primary-color);
  }
}
.order-footer {
  @apply cursor-pointer border-b py-1;
}
:deep(.ant-tabs-content-holder) {
  overflow: hidden;
}
.discount-input {
  :deep(.ant-input) {
    text-align: right;
  }
}
.color-placeholder {
  color: var(--disabled-text-color);
}
</style>
